import { Avatar, Badge, Button, Popover } from 'antd'
import cs from 'classnames'
import Image from 'next/image'
import { useRouter } from 'next/router'
import { useContext, useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import { LoginOut, Profile } from '@/api/modules/entity'
import { Notice } from '@/api/modules/home'
import AvatarPng from '@/assets/images/Avatar.png'
import Home from '@/assets/svg/Home.svg'
import MyTasks from '@/assets/svg/MyTasks.svg'
import User from '@/assets/svg/User.svg'
import { GlobalContext } from '@/context'
import { useRoute } from '@/routes'
import store, { GlobalState } from '@/store'
import checkLogin from '@/utils/checkLogin'
import eventBus from '@/utils/EventBus'
import useIsMountedRef from '@/utils/useIsMountedRef'
import useLocale from '@/utils/useLocale'

import EditName, { EditModalRef } from './EditName'
import locale from './locale'
import styles from './styles/index.module.less'

function getIconFromKey(path: string) {
  const className = styles['icon']
  switch (path) {
    case '/home':
      return <Home className={className} />
    case '/myTasks':
      return <MyTasks className={className} />
    case '/user':
      return <User className={className} />
  }
}

export default function Header() {
  const { setLang, lang } = useContext(GlobalContext)
  const t = useLocale(locale)

  const { authorities, userInfo, token } = useSelector((state: GlobalState) => state)

  const [routes] = useRoute(authorities)
  const router = useRouter()

  const isMountedRef = useIsMountedRef()

  // console.log(router.pathname) // 当前页面的路径
  // console.log(router.query) // 当前页面的查询参数
  // console.log(router.asPath) // 当前页面的完整 URL

  const pathname = router.pathname

  const toPath = (path: string) => {
    router.push(path)
  }

  const [noticeNum, setNoticeNum] = useState<number>(0)

  let timer: NodeJS.Timeout
  const getNoticeNum = async () => {
    try {
      const { data } = await Notice()
      if (noticeNum < data) {
        eventBus.emit('NEWKNOTICE')
      }
      setNoticeNum(data)
    } finally {
      if (timer) {
        clearTimeout(timer)
      }
      if (!!token) {
        timer = setTimeout(() => {
          getNoticeNum()
        }, 15000)
      }
    }
  }

  useEffect(() => {
    const pathname = router.pathname
    if (!checkLogin()) {
      router.replace('/entity')
    }
    console.log(pathname)
  }, [router])

  useEffect(() => {
    console.log(token)
    if (!!token) {
      getNoticeNum()
      Profile().then((res) => {
        console.log(res.data)
        const { authorities } = res.data
        const roles = authorities.map((a: { authority: string }) => a.authority)
        store.dispatch({
          type: 'update-authorities',
          payload: {
            authorities: roles,
          },
        })
      })
    } else {
      eventBus.off('CLICKNOTICE', getNoticeNum)
      if (timer) {
        clearTimeout(timer)
      }
    }

    eventBus.on('CLICKNOTICE', getNoticeNum)
    return () => {
      eventBus.off('CLICKNOTICE', getNoticeNum)
      if (timer) {
        clearTimeout(timer)
      }
    }
  }, [token])

  function logout() {
    LoginOut().finally(() => {
      store.dispatch({
        type: 'reset',
      })
    })

    router.replace('/entity')
  }

  const editRef = useRef<EditModalRef>(null)

  const items = (
    <>
      <div className="text-[#7c7d7d] pb-2">
        <span>{lang == 'en-US' ? userInfo?.entityName : userInfo?.entityNameAr}</span>
        {authorities?.includes('ROLE_ADMIN') && (
          <span
            className="text-[#44C5E4] underline cursor-pointer ml-2 mr-2"
            onClick={() => editRef.current?.showModal()}
          >
            {t['edit']}
          </span>
        )}
      </div>
      <Button type="link" onClick={logout} size="small" style={{ padding: 0 }}>
        <span className="text-[#16202d]">{t['loginOut']}</span>
      </Button>
      <EditName ref={editRef} />
    </>
  )

  return (
    <>
      <div className="w-full h-[60px]"></div>
      <header className={cs(styles['header'], 'w-full flex justify-center h-[60px] top-0 ')}>
        <div className="w-full flex items-center justify-between px-[61px]  max-w-[1440px] max-auto">
          <div className={cs('flex h-[60px] items-center')}>
            <Image src="/logo.svg" alt="logo Logo" width={89} height={36} priority />
            {isMountedRef.current ? (
              <div className={cs('flex h-60px px-14')}>
                {routes.map((a, k) => (
                  <div
                    key={k}
                    className={cs(
                      ' h-[60px] cursor-pointer',
                      styles['nav-item'],
                      a.path === pathname ? styles['active'] : ''
                    )}
                    onClick={() => {
                      toPath(a.path)
                    }}
                  >
                    {a.name === 'myTasks' ? (
                      <>
                        <Badge count={noticeNum} offset={[0, 0]} size="small">
                          <div className="flex items-center text-[18px]">
                            {getIconFromKey(a.path)}
                            <span
                              className={cs(
                                'px-2',
                                styles['span'],
                                lang == 'en-US' ? 'Roboto' : 'Cairo'
                              )}
                            >
                              {t[a.name]}
                            </span>
                          </div>
                        </Badge>
                      </>
                    ) : (
                      <>
                        {getIconFromKey(a.path)}
                        <span className={cs('px-2', lang == 'en-US' ? 'Roboto' : 'Cairo')}>
                          {t[a.name]}
                        </span>
                      </>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <></>
            )}
          </div>
          <div className="flex items-center">
            <div
              className={cs(
                styles['header-lang'],
                'flex items-center cursor-pointer mx-4',
                lang == 'en-US' ? 'Cairo' : 'Roboto'
              )}
              onClick={() => {
                setLang(lang == 'en-US' ? 'ar-EG' : 'en-US')
              }}
            >
              <span className={cs('text-[15px] font-normal px-2 text-[#848484]')}>
                {t['header-lang']}
              </span>
              <Image src="/lang.png" alt="logo Logo" width={21} height={21} priority />
            </div>

            <Popover content={items} placement="bottom">
              <div className="flex items-center cursor-pointer">
                <Avatar
                  size={32}
                  src={<Image alt="avatar" src={AvatarPng} width={32} height={32} />}
                ></Avatar>
                <div className="px-1" suppressHydrationWarning>
                  {lang == 'en-US' ? userInfo?.fullName : userInfo?.fullNameAr}
                </div>
              </div>
            </Popover>
          </div>
        </div>
      </header>
    </>
  )
}
